import Config from './config'
import CheckLogin from './verification-login'
import Store from '../../store/index'
import Api from '../../api/index'
import imUtil from '@/utils/imUtil'
class Util {
	constructor() {
		this.reqLoginLocked = false
	}

	/**
	 * @param {Object} opts
	 * showLoading 默认不显示，true则显示加载中，可传自定义字符串
	 * hideLoading 是否加载完成则隐藏loading
	 */
	request(opts) {
		function showToast(msg) {
			if (!opts.hideToast) {
				uni.showToast({
					title: msg,
					icon: 'none'
				});
			}
		}
		return new Promise(async (resolve, reject) => {
			let rqObj = {
				url: `${Config.requestUrl}${opts.url}`,
			}
			rqObj.data = opts.data || {}
			rqObj.header = {
				'Content-Type': 'application/x-www-form-urlencoded'
			}
			opts.method && (rqObj.method = opts.method)
			if (opts.header) {
				let now = new Date().getTime()
				let expires = uni.getStorageSync('expires')
				let token = uni.getStorageSync('token')
				if (expires > now && token) {
					if (typeof opts.header === 'boolean') {
						rqObj.header = {
							...rqObj.header,
							token,
						}
					} else {
						rqObj.header = {
							...rqObj.header,
							token,
							...opts.header
						}
					}
				} else {
					reject('未登录')
					this.skipToLoginPage()
					return
				}
			}
			if (opts.userId) {
				let userInfo = await CheckLogin.checkUserInfo()
				rqObj.data.userId = userInfo.userId
			}
			if (opts.shopId) {
				let userInfo = await CheckLogin.checkUserInfo()
				rqObj.data.shopId = userInfo.shopId
			}
			if (opts.showLoading) {
				if (typeof opts.showLoading === 'boolean') {
					uni.showLoading({
						title: '加载中...'
					})
				} else {
					uni.showLoading({
						title: opts.showLoading
					})
				}
			}
			uni.request(rqObj).then(([err, data]) => {
				opts.hideLoading && uni.hideLoading()
				if (!err && data && data.data) { // 请求成功
					// console.log(data);
					let {
						data: {
							data: ret,
							msg,
							code
						}
					} = data
					if (code == 0) {
						if (typeof opts.checkData === 'boolean' && opts.checkData === false) {
							// 不验证返回数据是否存在或者是否为空，直接返回
							resolve(data.data)
						} else if (typeof opts.checkData === 'function') {
							// 传了验证函数
							let flag = opts.checkData(data.data)
							if (flag) {
								resolve(data.data)
							} else {
								reject('数据错误')
								// console.log('数据错误')
							}
						} else { // 没传默认进行验证，或者传了true
							resolve(data.data)
							// if (ret) {
							// 	resolve(data.data)
							// } else {
							// 	reject('数据错误')
							// }
						}
					} else if (code == 500 && (
							msg === '用户登录已过期,请重新登录' ||
							msg === '无数据访问权限')) { // 需要登录
						showToast(msg)
						reject(msg)
						this.skipToLoginPage()
					} else {
						// 请求成功，返回数据错误
						showToast(msg)
						reject(msg)
					}
					/*****************************/
				} else { // 请求失败
					if (!err) {
						showToast('error: 未知请求错误！')
						reject('error: 未知请求错误！')
					} else {
						showToast(JSON.stringify(err))
						reject(JSON.stringify(err))
					}
				}
			})
		})
	}

	skipToLoginPage() {
		let currentPage = getCurrentPages()
		if (currentPage[currentPage.length - 1].route !== 'pages/login/index') {
			uni.navigateTo({
				url: '/pages/login/index'
			})
		}
	}

	navigationTo(urlObj, type) {
		if (typeof urlObj[type] === 'string') {
			uni.navigateTo({
				url: urlObj[type]
			})
		} else if (typeof urlObj[type] === 'function') {
			urlObj[type]()
		} else {
			console.error('错误页面路径！');
		}
	}

	toast(title, icon = 'none', duration = 1500, success) {
		uni.showToast({
			title,
			icon,
			duration,
			success
		})
	}
	getLocation() {
		return new Promise((resolve, reject) => {
			uni.getLocation().then(([err, data]) => {
				// let latitude = 0,
				// 	longitude = 0;
				if (!err) {
					resolve({
						latitude: data.latitude,
						longitude: data.longitude
					})
				} else {
					this.toast('定位失败，请确认是否已授权')
					console.log(`定位失败！${JSON.stringify(err)}`)
					reject()
				}
			})
		})
	}

	/**
	 * 创建节流函数
	 */
	throttles(fn, delay) {
		let flag = false
		return function(params) {
			if (flag) return
			flag = true
			setTimeout(() => {
				flag = false
			}, delay)
			fn(params)
		}
	}
	/**
	 * 剪贴板
	 */
	clipboard(data) {
		return new Promise((resolve, reject) => {
			uni.setClipboardData({
				data,
				success: function() {
					uni.getClipboardData({
						success: function(res) {
							resolve(res.data)
						}
					});
				}
			})
		})
	}
	/**
	 * 退出登录
	 */
	logout() {
		Api.authLogout()
		uni.removeStorageSync('token')
		uni.removeStorageSync('expires')
		imUtil.clearImStorage()
		Store.commit('updateUserInfo', {})
		Store.commit('updateShopInfo', {})
		uni.reLaunch({
			url: '/pages/login/index'
		})
	}
	logoutOnLoginPage() {
		uni.removeStorageSync('token')
		uni.removeStorageSync('expires')
		imUtil.clearImStorage()
		Store.commit('updateUserInfo', {})
		Store.commit('updateShopInfo', {})
	}
	/**
	 * 拼接图片的域名
	 * @param {string | Array} obj
	 * @param {string} key 数组对象中需拼接对象的key值
	 */
	concatRequestUrl(data, key) {
		if (typeof data === 'string' && data.indexOf('http://') == -1 && data.indexOf('https://') == -1) {
			return `${Config.requestUrl}${data}`
		} else if (Array.isArray(data)) {
			data = data.map(item => {
				if (key) {
					item[key] = this.concatRequestUrl(item[key])
				} else {
					item = this.concatRequestUrl(item)
					// console.log(item);
				}
				return item
			})
			// console.log(data);
		}
		return data
	}
}

export default new Util()
